package io.shdxhl.simplerpc.code.netty.strategy.impl;

import io.shdxhl.simplerpc.client.provider.ServiceProvider;
import io.shdxhl.simplerpc.code.annotation.SimpleLoadBalance;
import io.shdxhl.simplerpc.code.netty.strategy.LoadBalanceStrategy;
import org.apache.commons.lang3.RandomUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 权重负载均衡
 */
@SimpleLoadBalance(strategy = "weight")
public class WeightLoadBalanceStrategy implements LoadBalanceStrategy {
    @Override
    public ServiceProvider select(List<ServiceProvider> serviceProviders) {
        List<ServiceProvider> newServiceProvides = new ArrayList<ServiceProvider>();
        for (ServiceProvider serviceProvider : serviceProviders) {
            //获取当前服务提供者的权重
            int weight = serviceProvider.getWeight();
            for(int i =0; i<weight; i++){
                newServiceProvides.add(serviceProvider);
            }
        }
        //在新的数组队列中命中随机概率
        int index = RandomUtils.nextInt(0, newServiceProvides.size());
        return newServiceProvides.get(index);
    }
}
